package org.http;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;

/**
 * @author andy
 */

@Slf4j
public class TinyWebServer {
    TinyConfig config;
    int port = 8888;
    private static TinyWebServer tinyWebServer = null;
    static TinyWebServer of() {
        return null != tinyWebServer ? tinyWebServer : new TinyWebServer();
    }
    TinyWebServer init(int port) {
        this.port = port;
        return this;
    }

    TinyWebServer init(TinyConfig tinyConfig) {
        this.config = tinyConfig;
        this.port = tinyConfig.getPort();
        return this;
    }


    public void startServer() throws IOException {
        Selector selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(port));
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        log.info("Start tiny server, listen port at: {}", port);


        while (true) {
            // 判断读取的数
            int readyNum = selector.select();
            if (readyNum == 0) {
                continue;
            }

            // 循环选择的key
            Iterator<SelectionKey> iteratorSelectionKey = selector.selectedKeys().iterator();
            while (iteratorSelectionKey.hasNext()) {
                SelectionKey selectionKey = iteratorSelectionKey.next();
                iteratorSelectionKey.remove();

                // 处理数据
                try {
                    HandleSocketData.of().handle(selectionKey,selector,serverSocketChannel);
                } catch (Exception e) {
                    selectionKey.cancel();
                    //selectionKey = null;
                    log.error(e.getMessage(), e);
                }
            }
        }
    }
}